<template>
	<view class="upload-logo">
		<!-- 上传卡券LOGO -->
		<view class="detail-tally-trace">
			<view class="detail-trace-title">卡券LOGO</view>
			<view class="detail-tally-imgs">
				<view class="grid-item-box" v-for="(item, index) in imgs" :key="index"
					@tap.stop="ViewImage(item.imgName)">
					<image :src="item.imgName" class="tally-img" mode="aspectFill" />
					<van-icon class="delete-icon" name="clear" @tap.stop="DelImg(index)" />
				</view>
				<view class="grid-item-box detail-tally-img-add" v-show="isAddImgShow" @tap.stop="ChooseImage">
					<van-icon class="add-icon" name="plus" />
				</view>
			</view>
		</view>

		<button class="upload-btn" @click="submitUpload">确认上传</button>
	</view>
</template>

<script>
	import apiRqs from "@/api/api-request.js";
	import {
		sha256
	} from 'js-sha256';
	export default {
		data() {
			return {
				imgs: [],
				isAddImgShow: true,
				imgData: {},
				logo_media: {},
			}
		},
		onLoad() {
			const logoMedia = uni.getStorageSync("logo_media");
			if (logoMedia) {
				this.logo_media = logoMedia;
				this.imgs = [{
					imgName: logoMedia.logo_url
				}];
				this.isAddImgShow = false;
			} else {
				this.logo_media = {
					logo_media_url: "",
					logo_url: ""
				};
			}
		},
		methods: {
			// 上传图片
			ChooseImage(index) {
				let imgs = this.imgs;
				let loginInfo = uni.getStorageSync("loginInfo");
				var that = this;
				uni.chooseImage({
					count: 1, //默认最多上传6张图片
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						if (res.errMsg == 'chooseImage:ok' && (res.tempFiles[0].size / 1024 > 2048)) {
							getApp().showToast('图片大小不能超过2M，请重新上传!');
							return false;
						}
						getApp().showLoading();
						const tempFilePaths = res.tempFilePaths;
						console.log('res', res);
						// 将上传的图片分别请求上传到服务器
						if ((imgs.length + tempFilePaths.length) == 1) {
							that.isAddImgShow = false;
						} else {
							that.isAddImgShow = true;
						}

						// 上传商户头像，获取图片地址
						let p1 = new Promise((resolve) => {
							uni.uploadFile({
								url: getApp().globalData.websiteUrl + "/api/v1/FileUpload",
								filePath: tempFilePaths[0],
								name: 'file',
								header: {
									'Authorization': ('Bearer ' + loginInfo.token) || ''
								},
								formData: {
									'fileType': 'WeiXinPay'
								},
								success: (uploadFileRes) => {
									let res = JSON.parse(uploadFileRes.data);
									let filePath = res.data[0].filePath;
									let newFilePath = filePath.replace(/\\/g, "/");
									let completePath = newFilePath + "/" + res.data[0]
										.fileName;
									console.log('上传图片结果', res, completePath);
									that.imgs.push({
										imgName: tempFilePaths[0]
									})
									resolve(completePath);
								}
							});
						})

						// 商户头像地址sha256加密
						p1.then(path => {
							apiRqs._imgSha256({
								"filePath": path
							}).then(response => {
								uni.hideLoading();
								console.log('商户头像地址sha256加密', response);
								const imgSha256 = response.data;
								let p = {
									"file": path,
									"meta": {
										"filename": "couponLogo.png",
										"sha256": imgSha256
									}
								};
								that.imgData = p;
								console.log('that.imgData', that.imgData);
								// apiRqs._imgUrlToBinary(path).then(result => {
								// 	uni.hideLoading();
								// 	console.log('图片转二进制结果', result);
								// 	if (result.code == 200) {

								// 	} else {
								// 		getApp().showToast(result.msg);
								// 	}

								// })
							})
						})



						// uni.getFileSystemManager().readFile({
						// 	filePath: tempFilePaths[0],
						// 	encoding: 'binary',
						// 	success(res) {
						// 		console.log('binary', res);
						// 		let binaryData = res.data;
						// 		let p = {
						// 			"file": binaryData,
						// 			"meta": {
						// 				"filename": "couponLogo.png",
						// 				"sha256": sha256(binaryData)
						// 			}
						// 		};
						// 		console.log('sha256后的数据', p);
						// 		that.imgData = p;
						// 		that.imgs.push({
						// 			imgName: tempFilePaths[0]
						// 		})

						// 	}
						// })
						// for (let i = 0; i < tempFilePaths.length; i++) {
						// getApp().showLoading();
						// uni.uploadFile({
						// 	url: getApp().globalData.websiteUrl + "/api/v1/FileUpload",
						// 	filePath: tempFilePaths[i],
						// 	name: 'file',
						// 	header: {
						// 		'Authorization': ('Bearer ' + loginInfo.token) || ''
						// 	},
						// 	formData: {
						// 		'fileType': 'CheckImg'
						// 	},
						// 	success: (uploadFileRes) => {
						// 		let res = JSON.parse(uploadFileRes.data);
						// 		let filePath = res.data[0].filePath;
						// 		let newFilePath = filePath.replace(/\\/g, "/");
						// 		let imgName =
						// 			`${getApp().globalData.websiteUrl}${newFilePath}/${res.data[0].fileName}`;
						// 		let d = {
						// 			id: "0",
						// 			checkDetailId: "0",
						// 			imgName: `${getApp().globalData.websiteUrl}${newFilePath}/${res.data[0].fileName}`,
						// 			cover: "",
						// 			width: res.data[0].width,
						// 			height: res.data[0].height,
						// 			softDelete: false
						// 		}
						// 		console.log('imgFileData', d);
						// 		imgs.push(d);

						// 	}
						// });
						// }
						// that.imgs = imgs;

						// uni.hideLoading();
					}
				});
			},
			// 确认上传
			submitUpload() {
				getApp().showLoading();
				apiRqs._uploadCouponImg(this.imgData).then(result => {
					uni.hideLoading();
					console.log('图片上传结果', result);
					if (result.data.resultCode.stateCode == '200') {
						getApp().showToast("上传成功");
						uni.setStorageSync("logo_media", {
							logo_media_url: result.data.media_url,
							logo_url: getApp().globalData.websiteUrl + this.imgData.file
						});
						setTimeout(() => {
							uni.navigateBack();
						}, 2000)
					}
				})
			},
			// 预览图片
			ViewImage(imgName) {
				console.log('点击了预览');
				let imgs = this.imgs;
				var dataArray = [];
				for (var i = 0; i < imgs.length; i++) {
					dataArray[i] = imgs[i].imgName;
				}
				uni.previewImage({
					urls: dataArray,
					current: imgName
				});
			},
			// 删除图片
			DelImg(index) {
				this.imgs.splice(index, 1);
				if (this.imgs.length < 9) {
					this.isAddImgShow = true;
				} else if (this.imgs.length == 9) {
					this.isAddImgShow = false;
				} else {
					this.isAddImgShow = false;
				}
			},
		},
	}
</script>

<style lang="less">
	.upload-logo {
		.upload-btn {
			margin: 20px;
			border: none;
			background-color: #FFA53D;
			color: #fff;
			font-size: 15px;
			height: 35pt;
			line-height: 35pt;
			box-shadow: inset 0px 4px 7px 0px rgba(255, 255, 255, 0.33);

			&::after {
				border: none;
			}

			&:active {
				background-color: rgba(255, 141, 10, 1);
			}
		}

		.detail-tally-trace {
			margin-top: 10px;

			.detail-trace-title {
				font-size: 12px;
				color: #999999;
				margin-left: 20px;
			}

			.detail-tally-imgs {
				background-color: #fff;
				padding: 0px 20px 5px 20px;
				box-sizing: border-box;
				display: flex;
				flex-wrap: wrap;

				.grid-item-box {
					width: 100px;
					height: 100px;
					position: relative;
					margin-left: 15px;
					margin-top: 15px;

					&:nth-child(3n+1) {
						margin-left: 0;
					}

					.tally-img {
						width: 100%;
						height: 100%;
					}

					.play-icon-bg {
						position: absolute;
						top: 0;
						left: 0;
						width: 100%;
						height: 100%;
						background-color: rgba(0, 0, 0, 0.3);
						z-index: 20;

						.play-icon {
							position: absolute;
							top: 50%;
							left: 50%;
							font-size: 30px;
							color: #fff;
							margin-left: -15px;
							margin-top: -15px;
						}
					}

					.delete-icon {
						position: absolute;
						top: -10px;
						right: -10px;
						color: #FF1010;
						background-color: #fff;
						font-size: 22px;
						border-radius: 50%;
						z-index: 99;
					}

					&.detail-tally-img-add {
						text-align: center;
						line-height: 100px;
						border: 1px solid #efefef;
						box-sizing: border-box;

						.add-icon {
							font-size: 28px;
							color: #999999;
						}
					}
				}
			}

			.detail-remark {
				margin-top: 10px;
				background-color: #fff;
				padding: 10px 16px;
				box-sizing: border-box;
			}
		}
	}
</style>